<template>
  <PageHeaderWrapper>
    <a-card class="invoicing-theme card">
      <div class="header">
        <div class="header-top">
          <div class="header-top-left">
            <div class="header-top-item">
              供应商:
              <a-input v-model="search.supplierName" placeholder="请输入" class="input-width"/>
            </div>
            <div class="header-top-item">
              <div style="padding-left: 14px">类别:</div>
              <a-select v-model="search.type" placeholder="请选择" class="input-width">
                <a-spin slot="notFoundContent" size="small" />
                <a-select-option v-for="item in typeList" :key="item" :value="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </div>
            <div class="header-top-item">
              创建日期:
              <a-date-picker v-model="search.createTime" class="input-width" placeholder="请选择日期"/>
            </div>
          </div>
          <div class="header-top-right">
            <a-button type="primary" icon="search" @click="handleRefreshAndSearch">搜索</a-button>
            <a-button type="primary" :disabled="disabled" icon="sync" @click="resetSearch">重置</a-button>
          </div>
        </div>
      </div>
    </a-card>
    <a-card>
      <a-row class="table-operations">
        <a-col :span="2">
          <a-button type="primary" icon="plus" @click="showModal('添加供应商')">
            添加
          </a-button>
        </a-col>
        <a-col :span="3">
          <a-button type="primary" icon="reload" @click="handleRefreshAndSearch">
            刷新
          </a-button>
        </a-col>
      </a-row>
      <a-row>
        <a-alert showIcon style="margin-bottom: 10px">
          <template slot="message">
            <span style="margin-right: 12px">已选择: <a style="font-weight: 600">{{ table.selectedRowKeys.length }}</a>项</span>
            <a style="margin-left: 20px" @click="deleteBatch" v-if="table.selectedRowKeys.length > 0">批量删除</a>
            <a style="margin-left: 20px" @click="clearSelected" v-if="table.selectedRowKeys.length > 0">清空</a>
          </template>
        </a-alert>
        <a-table
          :columns="columns"
          :data-source="table.dataSource"
          :pagination="table.pagination"
          :loading="table.loading"
          rowKey="id"
          @change="handleTableChange"
          :rowSelection="{ selectedRowKeys: table.selectedRowKeys, onChange: handleSelectChange }"
        >
          <template slot="operation" slot-scope="text, record">
            <a @click="edit(record)">编辑</a>
            <span class="delete">
              <a-popconfirm
                title="确定要删除该供应商吗？"
                ok-text="Yes"
                cancel-text="No"
                @confirm="deleteConfirm(record.id)"
              >
                <a>删除</a>
              </a-popconfirm>
            </span>
          </template>
        </a-table>
      </a-row>
      <a-modal
        :title="modal.title"
        width="420px"
        :visible="modal.visible"
        :confirm-loading="modal.confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 15 }">
          <a-form-item label="供应商" has-feedback>
            <a-input
              v-decorator="['name', {
                rules: [{ required: true, message: '请输入客户名!' }],
                initialValue: modal.defaultSupplier
              }]"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="分类" has-feedback>
            <a-input
              v-decorator="['type', {
                rules: [{ required: true, message: '请输入分类!' }],
                initialValue: modal.defaultType
              }]"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="联系人" has-feedback>
            <a-input
              v-decorator="['contact', {
                rules: [{ required: true, message: '请输入联系人!' }],
                initialValue: modal.defaultContactName
              }]"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="电话" has-feedback>
            <a-input
              v-decorator="['telephone', {
                rules: [{ required: true, message: '请输入联系电话!' }],
                initialValue: modal.defaultTelephone
              }]"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="省市区选择" has-feedback>
            <cascaderProvince
              v-decorator="['city', {
                rules: [{ type: 'array', required: true, message: '请选择所在省市区!' }],
                initialValue: modal.defaultProvince
              }]"
              @myevent="setCityData"
              :defaultProvince="modal.defaultProvince"
            >
            </cascaderProvince>
          </a-form-item>
          <a-form-item label="详细地址" has-feedback>
            <a-textarea
              v-decorator="['concreteAddress', {
                rules: [{ required: true, message: '请输入详细地址!' }],
                initialValue: modal.defaultDetailAddress
              }]"
              placeholder="请输入"
              auto-size
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </PageHeaderWrapper>
</template>

<script>
import { PageHeaderWrapper } from '@ant-design-vue/pro-layout'
import {
  addSupplier,
  deleteSupplier,
  listSupplier,
  typeListSupplier,
  updateSupplier
} from '@/api/supplierManage'
import moment from 'moment'
import cascaderProvince from '@/views/systemManage/components/cascaderProvince'

const defaultPagination = {
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '15', '20'],
  showTotal: total => `总共 ${total} 条数据`
}

export default {
  name: 'SupplierManage',
  components: { PageHeaderWrapper, cascaderProvince },
  mounted () {
    this.getSupplierList()
    this.getTypeList()
  },
  computed: {
    columns () {
      return [
        {
          title: '供应商',
          dataIndex: 'name',
          align: 'center',
          key: 'name'
        },
        {
          title: '所在省市',
          dataIndex: 'city',
          align: 'center',
          key: 'city',
          customRender: (text, record, index) => JSON.parse(text).join(' ')
        },
        {
          title: '详细地址',
          dataIndex: 'concreteAddress',
          align: 'center',
          key: 'concreteAddress'
        },
        {
          title: '联系人',
          dataIndex: 'contact',
          align: 'center',
          key: 'contact'
        },
        {
          title: '电话',
          dataIndex: 'telephone',
          align: 'center',
          key: 'telephone'
        },
        {
          title: '分类',
          dataIndex: 'type',
          align: 'center',
          key: 'type'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align: 'center',
          sorter: true,
          key: 'createTime'
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'operation' }
        }
      ]
    },
    disabled () {
      return !this.search.type && !this.search.contactName && !this.search.supplierName && !this.search.createTime
    }
  },
  data () {
    return {
      search: {
        supplierName: null,
        createTime: null,
        type: null
      },
      typeList: [],
      modal: {
        title: '',
        visible: false,
        confirmLoading: false,
        defaultSupplier: '',
        defaultType: '',
        defaultContactName: '',
        defaultTelephone: '',
        defaultProvince: null,
        defaultDetailAddress: '',
        defaultId: ''
      },
      table: {
        pagination: defaultPagination,
        loading: false,
        dataSource: [],
        sorter: null,
        selectedRowKeys: []
      },
      form: this.$form.createForm(this, { name: 'coordinated' })
    }
  },
  methods: {
    setCityData (data) {
      this.form.setFieldsValue({
        city: data
      })
    },
    deleteConfirm (id) {
      const _this = this
      deleteSupplier(id)
        .then(res => {
          _this.$message.success('删除成功')
          _this.handleRefreshAndSearch()
        })
        .catch(err => {
          _this.$message.error(err.response.data.msg || '删除失败')
        })
    },
    getSupplierList () {
      const _this = this
      const sorter = this.table.sorter || {}
      this.table.loading = true
      let crt = _this.search.createTime
      if (crt !== null) {
        crt = moment(_this.search.createTime).format('YYYY-MM-DD HH:mm:ss')
      }
      listSupplier({
        page: _this.table.pagination.current,
        pageSize: _this.table.pagination.pageSize,
        order: sorter.order,
        supplierName: _this.search.supplierName,
        type: _this.search.type,
        createTime: crt
      }).then(function (res) {
        _this.table.dataSource = res.data.list
        _this.table.pagination.total = res.data.total
      }).catch(function (err) {
        _this.$message.error(err.response.data.msg || '加载失败')
      }).finally(function () {
        _this.table.loading = false
      })
    },
    getTypeList () {
      const _this = this
      typeListSupplier().then(res => {
        _this.typeList = res.data.typeList
      }).catch(err => {
        _this.$message.error(err.response.data.msg)
      })
    },
    showModal (value) {
      this.modal.title = value
      this.modal.visible = true
    },
    resetSearch () {
      this.search.type = null
      this.search.createTime = null
      this.search.supplierName = null
    },
    edit (record) {
      this.modal.title = '编辑供应商'
      this.modal.defaultId = record.id
      this.modal.defaultSupplier = record.name
      this.modal.defaultContactName = record.contact
      this.modal.defaultTelephone = record.telephone
      this.modal.defaultProvince = JSON.parse(record.city)
      this.modal.defaultDetailAddress = record.concreteAddress
      this.modal.defaultType = record.type
      this.modal.visible = true
    },
    handleTableChange (pagination, filters, sorter) {
      this.table.pagination = pagination
      this.table.sorter = sorter
      this.getSupplierList()
    },
    handleOk (e) {
      this.modal.confirmLoading = true
      const _this = this
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.modal.title === '添加供应商') {
            addSupplier({
              name: values.name,
              type: values.type,
              contact: values.contact,
              telephone: values.telephone + 0,
              city: JSON.stringify(values.city),
              concreteAddress: values.concreteAddress
            })
              .then(function (res) {
                _this.modal.confirmLoading = false
                _this.handleCancel()
                _this.handleRefreshAndSearch()
                _this.$message.success('添加供应商成功')
                _this.getTypeList()
                _this.getSupplierList()
              })
              .catch(function (err) {
                _this.$message.error(err.response.data.msg || '添加失败')
                _this.modal.confirmLoading = false
            })
          } else if (this.modal.title === '编辑供应商') {
            updateSupplier({
              id: _this.modal.defaultId,
              name: values.name,
              type: values.type,
              contact: values.contact,
              telephone: values.telephone,
              city: JSON.stringify(values.city),
              concreteAddress: values.concreteAddress
            })
              .then(function (res) {
                _this.modal.confirmLoading = false
                _this.modal.visible = false
                _this.handleRefreshAndSearch()
                _this.$message.success('修改成功')
              })
              .catch(function (err) {
                _this.$message.error(err.response.data.msg)
                _this.modal.confirmLoading = false
              })
          }
        } else {
          _this.modal.confirmLoading = false
        }
      })
    },
    handleRefreshAndSearch () {
      this.table.pagination.current = 1
      this.getSupplierList()
    },
    handleCancel (e) {
      this.modal.defaultContactName = ''
      this.modal.defaultDetailAddress = ''
      this.modal.defaultProvince = null
      this.modal.defaultSupplier = ''
      this.modal.defaultTelephone = ''
      this.modal.defaultType = ''
      this.modal.visible = false
      this.form.resetFields()
    },
    handleSelectChange (selectedRowKeys) {
      this.table.selectedRowKeys = selectedRowKeys
    },
    deleteBatch () {

    },
    clearSelected () {
      this.handleSelectChange([])
    }
  }
}
</script>

<style lang="less" scoped>
.card{
  padding: 0 1rem;
}
.header{
  &-top{
    display: flex;
    justify-content: space-between;
    &-left{
      display: flex;
      flex: 4;
    }
    &-right{
      display: flex;
      flex: 1;
      align-items: center;
      justify-content: center;
      gap: 1rem;
    }
    &-item{
      flex:1;
      display: flex;
      align-items: center;
      gap: .3rem;
      &:nth-child(1){
        justify-content: left;
      }
      &:nth-child(2){
        justify-content: center;
      }
      &:nth-child(3){
        justify-content: right;
      }
    }
  }
}
.input-width{
  width: 70%
}
.table-operations{
  margin-bottom: 10px;
}
.delete{
  margin-left: 10px;
}
</style>
